/**
 * fengbin
 * 2008-12-27
 */
package com.wsj.util.tool;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wsj.service.IHomeSiteNewsServ;
import com.wsj.util.exception.BusinessException;
import com.wsj.util.page.PageResultSet;
import com.wsj.web.constant.homeSiteNews.HomeSiteNewsConstant;
import com.wsj.web.subclass.displayBean.HomeSiteNews.HomeSiteNewsFormExtendBean;
import com.wsj.web.vo.homeSite.HomeSiteNews;

/**
 * @author fengbin
 *  请求连接.
 */
public class HtmlCreateObjUrlConnect implements Runnable
{

	Log logger=LogFactory.getLog(this.getClass());
	
	 private HtmlCreateStack htmlCreateBean;
	
	 
	/** 资讯接口 */
	private IHomeSiteNewsServ homeSiteNewsServImpl;
	
	
	
	//请求链接
	private String connectUrl="http://www.qqddc.com/zxzx.do?method=toDetails&id=";
	
	//生成文件路径
	private String createFilePath="E:\\apache-tomcat-5.5.25\\webapps\\qqddc\\html\\news\\";
	
	public HtmlCreateObjUrlConnect()
	{
		
	}

   
	public String getCreateFilePath() {
		return createFilePath;
	}

	public void setCreateFilePath(String createFilePath) {
		this.createFilePath = createFilePath;
	}

	public String getConnectUrl() {
		return connectUrl;
	}

	public void setConnectUrl(String connectUrl) {
		this.connectUrl = connectUrl;
	}

	public HtmlCreateObjUrlConnect(HtmlCreateStack htmlCreateBean)
	{
		this.htmlCreateBean =htmlCreateBean;
	}
	
   public HtmlCreateStack getHtmlCreateBean() 
   {
		return htmlCreateBean;
	}


	public void setHtmlCreateBean(HtmlCreateStack htmlCreateBean) {
		this.htmlCreateBean = htmlCreateBean;
	}
	
	/*******
	 * 总的页码
	 */
	private Integer allPage;
	
	//显示数
	Integer pageSize = 100;
	
	

	public Log getLogger() {
		return logger;
	}

	public void setLogger(Log logger) {
		this.logger = logger;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public Integer getAllPage() {
		return allPage;
	}

	public void setAllPage(Integer allPage) {
		this.allPage = allPage;
	}

	public IHomeSiteNewsServ getHomeSiteNewsServImpl() {
		return homeSiteNewsServImpl;
	}

	public void setHomeSiteNewsServImpl(IHomeSiteNewsServ homeSiteNewsServImpl) {
		this.homeSiteNewsServImpl = homeSiteNewsServImpl;
	}

	/********
	 * 通过 url 获取字符串.
	 */
    public void run()
    {
    	
	  //也可以在这里用List循环
      for(int j=1;j<=allPage;j++)
      {
    	  try {
			    HomeSiteNewsFormExtendBean curBean = new HomeSiteNewsFormExtendBean();
				curBean.setPage(j);
				curBean.setPageSize(pageSize);
				
				//获取当前的结果集
				PageResultSet curPageResultSet=this.homeSiteNewsServImpl.loadHomeSiteNewsByExtendBean(curBean);
				List li = curPageResultSet.getResult();
				for(int t=0;t<li.size();t++)
				{
					try 
					{
						HomeSiteNews homeSiteNews = (HomeSiteNews)li.get(t);
						StringBuffer[] str=createFile(homeSiteNews);
						HtmlFileBean htmlFileBean =new HtmlFileBean();
						
						//生成文件的字符串
						htmlFileBean.setStringBuffer(str);
						htmlFileBean.setId(homeSiteNews.getId());
						htmlFileBean.setCreateFilePath(createFilePath);
						//将数据压入堆栈中
						htmlCreateBean.push(htmlFileBean);
							
						/*线程稍微休息几豪秒*/
						Thread.sleep((int)(200));
						    
					} 
					catch (Exception e) 
					{
						e.printStackTrace();
					}
					
				} 
			         
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
                     
          
     }
      
     }
    
    
    /****
	 * 生成静态页面.
	 *
	 */
	public synchronized StringBuffer[] createFile(HomeSiteNews homeSiteNews) 
	{
		StringBuffer[] bufs=null;
		String fileName = "";
		String spliter="<div style=\"page-break-after: always\"><span style=\"display: none\">&nbsp;</span></div>";
		List<String> contentslist=new ArrayList<String>();
		String con=homeSiteNews.getContent();
		if(con!=null&&!con.equals("")&&con.indexOf(spliter)!=-1){
			String[] contents=con.split(spliter);
			if(contents!=null&&contents.length>0){
				for(int i=0;i<contents.length;i++){
					if(contents[i]!=null&&!contents.equals("")){
						contentslist.add(contents[i]);
					}
				}
			}
		}else 
		{
			  //生成静态页面
			 fileName=HomeSiteNewsConstant.homeSiteNewsHead+homeSiteNews.getId()+"_"+String.valueOf(1)+".html";
			 StringBuffer stringBuffer = this.toHtmlFile(connectUrl+homeSiteNews.getId(), createFilePath, fileName);
			 bufs=new StringBuffer[1];
			 bufs[0]=stringBuffer;
			 
		}
		
		
		
		if(contentslist!=null&&!contentslist.isEmpty()&&contentslist.size()>0)
		{
			 bufs=new StringBuffer[contentslist.size()];
			for(int i=0;i<contentslist.size();i++){
				if(i==0)
				{
			        //生成静态页面
					fileName=HomeSiteNewsConstant.homeSiteNewsHead+homeSiteNews.getId()+"_"+String.valueOf(i+1)+".html";
					StringBuffer stringBuffer  = this.toHtmlFile(connectUrl+homeSiteNews.getId()+"&content="+i, createFilePath, fileName);
					bufs[i]=stringBuffer;
					
				}else 
				{
			        //生成静态页面
					fileName=HomeSiteNewsConstant.homeSiteNewsHead+homeSiteNews.getId()+"_"+String.valueOf(i+1)+".html";
					StringBuffer stringBuffer = this.toHtmlFile(connectUrl+homeSiteNews.getId()+"&content="+i, createFilePath, fileName);
					bufs[i]=stringBuffer;
				}
			}
			
		}
		
		return bufs;
     
	}
	
	
	/*********
	 * 文件到实际的静态页面
	 * 连接链接,完整文件路径,文件名
	 */
	public StringBuffer toHtmlFile(String connectUrl,String newFilePath,String fileName)
	{
		StringBuffer stringBuffer =new StringBuffer();
		InputStream  inputStream  = null;
//		BufferedOutputStream out = null;
		
		try {
			//检查生成的文件路径是否存在,如果不存在.则创建该文件路径.
			  File fileDir=new File(newFilePath);
				
			  //该文件夹不存在,则创建文件夹.
				if(!fileDir.exists())
				{
					if(!fileDir.mkdirs())
					{
						logger.info("\n\n\n文件夹创建失败");
					}
				}
 
			URL conUrl = new URL(connectUrl); 
            URLConnection connection = conUrl.openConnection(); 
            connection.connect(); 
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection; 
            int httpResult = httpURLConnection.getResponseCode(); 
            if (httpResult != HttpURLConnection.HTTP_OK)
            { 
            	logger.info("没有连接成功"); 
            }
            else 
            { 
            
            	  inputStream  = new BufferedInputStream(httpURLConnection.getInputStream());
            	
//            	  // 写入到数据流
//				  out=new BufferedOutputStream(new FileOutputStream(newFilePath+fileName));
				 //设置流数据包的大小
				   byte[] buffer=new byte[64 * 1024];
					int length;
					while((length=inputStream.read(buffer,0,buffer.length))>0)
					{
						//out.write(buffer,0,length);
						stringBuffer.append(new String(buffer,"UTF-8"));
					}
					
					
					logger.error("\n\n 文件流:"+stringBuffer.toString());
            }
            
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
		finally
		{
			try 
			{
//				//清除缓存
//				if(out != null){
//					out.flush();
//					out.close();
//				}			
				if(inputStream != null){
					inputStream.close();
				}				
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
				logger.error("\n\n关闭流异常!");
			}
			
		}
		
		return stringBuffer;
        
	}
    

}
 